package jeecg.business.service.impl.keyinfo;

import java.math.BigDecimal;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import jeecg.business.entity.alarm.AlarmWordEntity;
import jeecg.business.entity.enter.EnterEntity;
import jeecg.business.entity.keyinfo.KeyinfoEntity;
import jeecg.business.entity.keyinfo.KeyinfoTextEntity;
import jeecg.business.entity.keyword.KeywordEntity;
import jeecg.business.entity.province.ProvinceEntity;
import jeecg.business.job.FetchTask;
import jeecg.business.service.alarm.AlarmWordServiceI;
import jeecg.business.service.keyinfo.KeyinfoServiceI;
import jeecg.business.service.keyword.KeywordServiceI;
import jeecg.business.service.province.ProvinceServiceI;
import jeecg.business.service.setting.NmsSystemSettingServiceI;
import jeecg.business.vo.CommonAnalysisVo;
import jeecg.business.vo.ContainWordNum;
import jeecg.business.vo.RefwordVo;
import jeecg.business.vo.TimeLastAnalysisVo;
import jeecg.business.vo.TypeAnalysisVo;
import jeecg.business.vo.WordNumComparator;

import org.jeecgframework.core.common.model.json.DataGrid;
import org.jeecgframework.core.common.service.impl.CommonServiceImpl;
import org.jeecgframework.core.util.DataUtils;
import org.jeecgframework.core.util.StringUtil;
import org.jeecgframework.core.util.clean.bean.HtmlParseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service("keyinfoService")
@Transactional
public class KeyinfoServiceImpl extends CommonServiceImpl implements KeyinfoServiceI {
	
	@Autowired
	ProvinceServiceI provinceService;
	
	@Autowired
	AlarmWordServiceI alarmWordService;
	
	@Autowired
	NmsSystemSettingServiceI settingService;
	
	@Autowired
	KeywordServiceI keywordService;
	
	public List<KeyinfoEntity> list(String enterid , String sfsc){
		String hql = " from KeyinfoEntity where qyid = '"+enterid+"' and sfsc = '"+sfsc+"'";
		return findByQueryString(hql);
	}
	
	public void setStatus(String ids , String status){
		String sql = " update nms_key_info set sfsc = '"+status+"' where id in ('"+ids.replace(",", "','")+"')";
		getJdbcTemplate().execute(sql);
	}
	
	public List<KeyinfoEntity> listByTime(String enterid , String starttime , String keyword){
		String hql = " from KeyinfoEntity where qyid = '"+enterid+"' and eventdate >= '"+starttime+" 00:00:00' and keyword = '"+keyword+"' and sfsc ='0' ";
		return findByQueryString(hql);
	}
	
	public boolean hasHref(String url , String qyid){
		int count = getJdbcTemplate().queryForInt(" select count(1) from nms_key_info where yurl = '"+url+"' and qyid = '"+qyid+"'");
		return count > 0;
	}
	
	public boolean hasTitle(String title , String qyid){
		int count = getJdbcTemplate().queryForInt(" select count(1) from nms_key_info where title = ? and qyid = '"+qyid+"'" , title);
		return count > 0;
	}
	
	
	public void saveKeyinfo4Edit(KeyinfoEntity keyinfoEntity){
		if(StringUtil.isEmpty(keyinfoEntity.getTitle()) && StringUtil.isEmpty(keyinfoEntity.getBodycontent())) return;
		
		
		/**
		 * 设置负面词
		 */
		keyinfoEntity = setNegative4Edit(keyinfoEntity);
		keyinfoEntity.setSfjb("0");
		keyinfoEntity.setSfsc("0");
		keyinfoEntity.setSfyj("0");
		
		keyinfoEntity.setTitle(StringUtil.removeHTMLLable(keyinfoEntity.getTitle()));
		
		String qyid = keyinfoEntity.getQyid();
		EnterEntity enter = get(EnterEntity.class, qyid);
		setProvince(keyinfoEntity , enter);
		keyinfoEntity.setRefword(null);
		keyinfoEntity.setRefwordnum(null);
		KeywordEntity keywrod  = keywordService.get(qyid, keyinfoEntity.getKeyword());
		filter(enter , keyinfoEntity , keywrod);

		
		/**
		 * 重新减少关键字
		 */
		if(StringUtil.isNotEmpty(keyinfoEntity.getKeyword())){
			keyinfoEntity.setAllkeyword(keyinfoEntity.getKeyword());
			keyinfoEntity.setKeyword(keyinfoEntity.getKeyword());
		}
		
		save(keyinfoEntity);
		
		KeyinfoTextEntity text = new KeyinfoTextEntity();
		text.setId(keyinfoEntity.getId());
		text.setContent(keyinfoEntity.getBodycontent());
		saveOrUpdate(text);
		
	}
	
	boolean filter(EnterEntity enter , KeyinfoEntity keyinfo , KeywordEntity keyword){
		String ppnr = keyword.getPpnr();
		String bppgjc = keyword.getBppgjc();
		/**
		 * 设置不匹配关键词
		 */
		int bppnum = 0;
		
		String title = keyinfo.getTitle();
		String content = keyinfo.getBodycontent();
		if(title==null) title = "";
		if(content==null) content = "";
		
		if(StringUtil.isNotEmpty(bppgjc)){
			String [] bpps = bppgjc.split("\\|");
			for(String bpp : bpps){
				if(title.contains(bpp) || content.contains(bpp))
					bppnum++;
			}
		}
		/**
		 * 匹配内容
		 */
		String [] pps = ppnr.split("\\+");
		List<String> mustlist = new ArrayList<String>();
		List<ContainWordNum> wmlist = new ArrayList<ContainWordNum>();
		List<String> maylist = new ArrayList<String>();
		String [] mays = null;
		for(String pp : pps){
			if(pp.contains("|")){
				pp = pp.replace(")", "").replace("(", "").replace("（", "").replace("）", "");
				mays = pp.split("\\|");
				for(String may : mays)
					maylist.add(may);
			}else{
				mustlist.add(pp);
			}
		}
		
		boolean flag = true;
		for(String must : mustlist)
			flag = flag && (title.contains(must) || content.contains(must));
		
		String mayStr = null;
		ContainWordNum wn = null;
		for(String may : maylist){
			if(title.contains(may) || content.contains(may)){		//添加次数
				int count = 0;
				count = StringUtil.getStrAppearNum(title, may);
				count += StringUtil.getStrAppearNum(content, may);
				wn = new ContainWordNum();
				wn.setWord(may);
				wn.setNum(count);
				wmlist.add(wn);
			}
		}
		
		Collections.sort(wmlist, new WordNumComparator());
		String refwordnum = null;
		for(ContainWordNum c : wmlist){
			if(mayStr == null){
				mayStr = c.getWord();
				refwordnum = c.getNum()+"";
			}
			else{
				mayStr += "|"+c.getWord();
				refwordnum += "|"+c.getNum();
			}
			
		}
		
		flag = flag && mayStr!=null;
		
		if(flag){
			keyinfo.setRefword(mayStr);
			keyinfo.setRefwordnum(refwordnum);
			keyinfo.setKeyword(keyword.getKeyword());
		}
		
		return flag;
	}
	
	
	
	KeyinfoEntity setNegative4Edit(KeyinfoEntity keyinfoEntity){
		float fmz = 0.0f;
		String fc = null;
		String fccs = null;
		if(FetchTask.alarmList == null) FetchTask.alarmList = alarmWordService.loadAll(AlarmWordEntity.class);
		if(FetchTask.alarmList != null){
			for(AlarmWordEntity alarm : FetchTask.alarmList)
				if((StringUtil.isNotEmpty(keyinfoEntity.getTitle()) && keyinfoEntity.getTitle().contains(alarm.getCy()))
						|| (StringUtil.isNotEmpty(keyinfoEntity.getBodycontent()) && keyinfoEntity.getBodycontent().contains(alarm.getCy()))){
					int countnum = 0;
					countnum = StringUtil.getStrAppearNum(keyinfoEntity.getTitle(), alarm.getCy());
					countnum += StringUtil.getStrAppearNum(keyinfoEntity.getBodycontent(), alarm.getCy());
					fmz += alarm.getQzz();//*countnum;
					if(fc == null){
						fc = alarm.getCy();
						fccs = ""+countnum;
					}
					else{
						fc += " "+alarm.getCy();
						fccs += " "+countnum;
					} 
				}
			keyinfoEntity.setFmz(fmz);
			keyinfoEntity.setFmc(fc);
			keyinfoEntity.setFmccs(fccs);
		}
		return keyinfoEntity;
	}
	
	public void saveKeyinfo(KeyinfoEntity keyinfoEntity){
		int count = 0;
		
		if(StringUtil.isEmpty(keyinfoEntity.getTitle()) && StringUtil.isEmpty(keyinfoEntity.getBodycontent())) return;
		
		
		
		keyinfoEntity = setNegative(keyinfoEntity);
		keyinfoEntity.setSfjb("0");
		keyinfoEntity.setSfsc("0");
		keyinfoEntity.setSfyj("0");
		
		/**
		 * 设置标题
		 */
		keyinfoEntity.setTitle(StringUtil.removeHTMLLable(keyinfoEntity.getTitle()));
	
		
		KeyinfoEntity enterKey = null;
		enterKey = keyinfoEntity.clone();
		String qyid = keyinfoEntity.getQyid();
		EnterEntity enter = get(EnterEntity.class, qyid);
		setProvince(enterKey , enter);
//		if("wb".equals(enterKey.getType())){
//			count = getJdbcTemplate().queryForInt(" select count(1) from nms_key_info where bodycontent = '"+enterKey.getBodycontent()+"' and qyid = '"+enterKey.getQyid()+"'");
//		}else{
		count = getJdbcTemplate().queryForInt(" select count(1) from nms_key_info where yurl = '"+enterKey.getYurl()+"' and qyid = '"+enterKey.getQyid()+"'");
		if("2".equals(keyinfoEntity.getPcfs())){
			String title = StringUtil.removeFlag(enterKey.getTitle());
			enterKey.setTitle(title);
			count += getJdbcTemplate().queryForInt(" select count(1) from nms_key_info where title = '"+enterKey.getTitle()+"' and qyid = '"+enterKey.getQyid()+"'");
		}
//		}
		if(count == 0){
			/**
			 * 重新减少关键字
			 */
			enterKey.setAllkeyword(enterKey.getKeyword());
			enterKey.setKeyword(enterKey.getKeyword());
			System.out.println("------"+enterKey.getTitle());
			save(enterKey);
			
			KeyinfoTextEntity text = new KeyinfoTextEntity();
			text.setId(enterKey.getId());
			text.setContent(enterKey.getBodycontent());
			save(text);
		}
		
	}
	
	void setProvince(KeyinfoEntity keyinfoEntity , EnterEntity enter){
//		keyinfoEntity.setSf(enter.getSf());
		
		String title = keyinfoEntity.getTitle();
		String content = keyinfoEntity.getBodycontent();
		if(content == null) content = "";
		String refword = null;
		String name = null;
		String pname = null;
		if(FetchTask.provinceList == null) FetchTask.provinceList = provinceService.loadAll(ProvinceEntity.class);
		
		int maxtime = 0;
		String rightname = "";
		/**
		 * 省份没有找到，找市县
		 */
		if(pname == null){
			String [] words = null;
			for(ProvinceEntity province : FetchTask.provinceList){		//计算出现的次数
				//if(pname != null) break;			//找到就跳出
				int time = 0;
				name = province.getProvince();
				refword = name+"|"+province.getRefword();
				words = refword.split("\\|");
				for(String word : words){
					if((title.contains(word) || content.contains(word)) && StringUtil.isNotEmpty(word)){
						time += StringUtil.getStrAppearNum(title , word)*3+StringUtil.getStrAppearNum(content , word);
						pname = name;
					}
				}
				if(time >= maxtime){
					rightname = name;
					maxtime = time;
				}
			}
		}
		String sf = null;
		if(rightname != null)
			sf = HtmlParseResult.sfMap.get(rightname);
		if(sf == null) sf = "其他";
		keyinfoEntity.setSf(sf);
	}
	
	
	/**
	 * 
	 * <p>
	 * 方法简要描述: 设置警戒值
	 * </p>
	 * <p>
	 * 方法详细描述: // TODO
	 * </p>
	 * 
	 * @author LinYingPiaoJian(Q:71426052)
	 * @version 
	 * @see
	 * @param keyinfoEntity
	 * @return
	 */
	KeyinfoEntity setNegative(KeyinfoEntity keyinfoEntity){
		float fmz = 0.0f;
		String fc = null;
		String fccs = null;
		if(FetchTask.alarmList != null){
			for(AlarmWordEntity alarm : FetchTask.alarmList)
				if((StringUtil.isNotEmpty(keyinfoEntity.getTitle()) && keyinfoEntity.getTitle().contains(alarm.getCy()))
						|| (StringUtil.isNotEmpty(keyinfoEntity.getBodycontent()) && keyinfoEntity.getBodycontent().contains(alarm.getCy()))){
					int countnum = 0;
					countnum = StringUtil.getStrAppearNum(keyinfoEntity.getTitle(), alarm.getCy());
					countnum += StringUtil.getStrAppearNum(keyinfoEntity.getBodycontent(), alarm.getCy());
					fmz += alarm.getQzz();//*countnum;
					if(fc == null){
						fc = alarm.getCy();
						fccs = ""+countnum;
					}
					else{
						fc += " "+alarm.getCy();
						fccs += " "+countnum;
					} 
				}
			keyinfoEntity.setFmz(fmz);
			keyinfoEntity.setFmc(fc);
			keyinfoEntity.setFmccs(fccs);
			if(fmz >= FetchTask.setting.getZmyz()){	//	正面值
				keyinfoEntity.setFmjb("-1");
			}else if(fmz <= 0-FetchTask.setting.getYzyz()){		//严重
				keyinfoEntity.setFmjb("3");
			}else if(fmz <= 0-FetchTask.setting.getZdyz()){		//中度
				keyinfoEntity.setFmjb("2");
			}else if(fmz <= 0-FetchTask.setting.getQdyz()){		//轻度
				keyinfoEntity.setFmjb("1");
			}else{
				keyinfoEntity.setFmjb("0");
			}
				
		}
		return keyinfoEntity;
	}
	
	public List<TypeAnalysisVo> analysis4Fmjb(String enterid , KeyinfoEntity keyinfo){
		List<TypeAnalysisVo> typeList = new ArrayList<TypeAnalysisVo>();
		Date date = new Date();
		
		Date endtime = date;
		
		Calendar cl = Calendar.getInstance();
		cl.setTime(date);
		
		if(keyinfo != null && StringUtil.isNotEmpty(keyinfo.getStarttime())){
			
			cl.setTime(DataUtils.parseDate(keyinfo.getStarttime(), "yyyy-MM-dd"));
			endtime = DataUtils.parseDate(keyinfo.getEndtime(), "yyyy-MM-dd");
			
		}else{
			cl.add(Calendar.DAY_OF_MONTH, -7);
		}
		
		String sql = " select fmjb , " +
		" case when type = 'lt' then count(1) end ltnum , "+
		" case when type = 'wb' then count(1) end wbnum , "+
		" case when type = 'ssyq' then count(1) end ssyqnum , "+
		" case when type = 'wx' then count(1) end wxnum , "+
		" case when type = 'xwmh' then count(1) end xwmhnum , "+ 
		" case when type = 'bk' then count(1) end bknum," +
		" case when type = 'sp' then count(1) end spnum "+
		" from nms_key_info  ";
		sql += " where eventdate >= '"+keyinfo.getStarttime()+" 00:00:00' and eventdate <= '"+keyinfo.getEndtime()+" 23:59:59'  and sfsc ='0' ";
		sql += " and qyid = '"+enterid+"' ";
		if(keyinfo != null){
			if(StringUtil.isNotEmpty(keyinfo.getKeyword())){
				sql += " and keyword like '%"+keyinfo.getKeyword()+"%'";
			}
			
			if(StringUtil.isNotEmpty(keyinfo.getKeywordtype())){
				sql += " and keyword in ( select keyword from nms_key_word where lx = '"+keyinfo.getKeywordtype()+"')";
			}
		}
			
		sql += " group by fmjb , type order by fmjb ";
		List<Map<String , Object>> list = getJdbcTemplate().queryForList(sql);
		
		TypeAnalysisVo vo = null;
		
		Map<String , TypeAnalysisVo> datamap = new HashMap<String , TypeAnalysisVo>();
		
		String time = null;
		
		vo = new TypeAnalysisVo();vo.setTime("-1");datamap.put("-1", vo);typeList.add(vo);
		vo = new TypeAnalysisVo();vo.setTime("0");datamap.put("0", vo);typeList.add(vo);
		vo = new TypeAnalysisVo();vo.setTime("1");datamap.put("1", vo);typeList.add(vo);
		vo = new TypeAnalysisVo();vo.setTime("2");datamap.put("2", vo);typeList.add(vo);
		vo = new TypeAnalysisVo();vo.setTime("3");datamap.put("3", vo);typeList.add(vo);
		
		
	
		
		/**
		 * 设置值
		 */
		String fmjb = null;
		for(Map<String , Object> data : list){
			fmjb = (String)data.get("fmjb");
			vo = datamap.get(fmjb);
			if(data.get("ltnum") != null) vo.setLt((Long)data.get("ltnum"));
			if(data.get("wxnum") != null) vo.setWx((Long)data.get("wxnum"));
			if(data.get("ssyqnum") != null) vo.setSsyq((Long)data.get("ssyqnum"));
			if(data.get("bknum") != null) vo.setBk((Long)data.get("bknum"));
			if(data.get("xwmhnum") != null) vo.setXwmh((Long)data.get("xwmhnum"));
			if(data.get("wbnum") != null) vo.setWb((Long)data.get("wbnum"));
			if(data.get("spnum") != null) vo.setSp((Long)data.get("spnum"));
		}		
		return typeList;
	}
	
	
	
	public List<TypeAnalysisVo> analysisLastWeek4Type(String enterid , KeyinfoEntity keyinfo){
		List<TypeAnalysisVo> typeList = new ArrayList<TypeAnalysisVo>();
		Date date = new Date();
		
		Date endtime = date;
		
		Calendar cl = Calendar.getInstance();
		cl.setTime(date);
		
		if(keyinfo != null && StringUtil.isNotEmpty(keyinfo.getStarttime())){
			
			cl.setTime(DataUtils.parseDate(keyinfo.getStarttime(), "yyyy-MM-dd"));
			endtime = DataUtils.parseDate(keyinfo.getEndtime(), "yyyy-MM-dd");
			
		}else{
			cl.add(Calendar.DAY_OF_MONTH, -7);
		}
		
		String sql = " select DATE_FORMAT(eventdate , '%Y-%m-%d') as eventdate2 , " +
		" case when type = 'lt' then count(1) end ltnum , "+
		" case when type = 'wb' then count(1) end wbnum , "+
		" case when type = 'ssyq' then count(1) end ssyqnum , "+
		" case when type = 'wx' then count(1) end wxnum , "+
		" case when type = 'xwmh' then count(1) end xwmhnum , "+ 
		" case when type = 'bk' then count(1) end bknum," +
		" case when type = 'sp' then count(1) end spnum "+
		" from nms_key_info  ";
		sql += " where eventdate >= '"+keyinfo.getStarttime()+" 00:00:00' and eventdate <= '"+keyinfo.getEndtime()+" 23:59:59'  and sfsc ='0' ";
		sql += " and qyid = '"+enterid+"' ";
		if(keyinfo != null){
			if(StringUtil.isNotEmpty(keyinfo.getKeyword())){
				sql += " and keyword like '%"+keyinfo.getKeyword()+"%'";
			}
			
			if(StringUtil.isNotEmpty(keyinfo.getKeywordtype())){
				sql += " and keyword in ( select keyword from nms_key_word where lx = '"+keyinfo.getKeywordtype()+"')";
			}
		}
		
		
			
		sql += " group by eventdate2 , type order by eventdate2 ";
		List<Map<String , Object>> list = getJdbcTemplate().queryForList(sql);
		
		TypeAnalysisVo vo = null;
		
		Map<String , TypeAnalysisVo> datamap = new HashMap<String , TypeAnalysisVo>();
		
		String time = null;
		
		while(cl.getTime().getTime()<=endtime.getTime()){
			vo = new TypeAnalysisVo();
			date = cl.getTime();
			time = DataUtils.formatDate(date, "yyyy-MM-dd");
			vo.setTime(time);
			cl.add(Calendar.DAY_OF_YEAR, 1);
			datamap.put(time, vo);
			typeList.add(vo);
		}
		
		/**
		 * 设置值
		 */
		String eventdate = null;
		for(Map<String , Object> data : list){
			eventdate = (String)data.get("eventdate2");
			vo = datamap.get(eventdate);
			if(data.get("ltnum") != null) vo.setLt((Long)data.get("ltnum"));
			if(data.get("wxnum") != null) vo.setWx((Long)data.get("wxnum"));
			if(data.get("ssyqnum") != null) vo.setSsyq((Long)data.get("ssyqnum"));
			if(data.get("bknum") != null) vo.setBk((Long)data.get("bknum"));
			if(data.get("xwmhnum") != null) vo.setXwmh((Long)data.get("xwmhnum"));
			if(data.get("wbnum") != null) vo.setWb((Long)data.get("wbnum"));
			if(data.get("spnum") != null) vo.setSp((Long)data.get("spnum"));
		}		
		return typeList;
	}
	
	public List<CommonAnalysisVo> analysisTime(String enterid , KeyinfoEntity keyinfo){
		String sql = "select DATE_FORMAT(eventdate,'%Y年%m月%d日') as name , count(1) as value  from nms_key_info ";
		sql += " where eventdate >= '"+keyinfo.getStarttime()+" 00:00:00' and eventdate <= '"+keyinfo.getEndtime()+" 23:59:59'  and sfsc ='0' ";
		sql += " and qyid = '"+enterid+"' ";
		if(keyinfo != null){
			if(StringUtil.isNotEmpty(keyinfo.getKeyword())){
				sql += " and keyword like '%"+keyinfo.getKeyword()+"%'";
			}
			
			if(StringUtil.isNotEmpty(keyinfo.getKeywordtype())){
				sql += " and keyword in ( select keyword from nms_key_word where lx = '"+keyinfo.getKeywordtype()+"')";
			}
		}
		sql += " group by name order by name asc";
		
		
		
		return findObjForJdbc(sql, 0, 0, CommonAnalysisVo.class, true);
	}
	
	public List<TypeAnalysisVo> analysisLastWeek4Type(String enterid){
		return analysisLastWeek4Type(enterid , null);
	}
	
	public TypeAnalysisVo analysisDay4Type(String enterid , KeyinfoEntity keyinfo , Date date){
		TypeAnalysisVo vo = new TypeAnalysisVo();
		String sql = "select type , count(1) num from nms_key_info i";
		String datestr = DataUtils.formatDate(date, "yyyy-MM-dd");
		vo.setTime(datestr);
		sql += " where  i.qyid = '"+enterid+"' and eventdate >= '"+datestr+" 00:00:00' and eventdate <= '"+datestr+" 23:59:59'  and sfsc ='0' ";
		if(keyinfo != null){
			if(StringUtil.isNotEmpty(keyinfo.getKeyword()))
				sql += " and i.keyword like '%"+keyinfo.getKeyword()+"%' ";
		}
		sql += "group by type";
		List<Map<String , Object>> list = getJdbcTemplate().queryForList(sql);
		if(list != null){
			String type = null;
			for(Map<String , Object> map : list){
				type = (String)map.get("type");
				if(type.equals("ssyq")) vo.setSsyq((Long)map.get("num"));
				if(type.equals("xwmh")) vo.setXwmh((Long)map.get("num"));
				if(type.equals("lt")) vo.setLt((Long)map.get("num"));
				if(type.equals("bk")) vo.setBk((Long)map.get("num"));
				if(type.equals("wb")) vo.setWb((Long)map.get("num"));
				if(type.equals("wx")) vo.setWx((Long)map.get("num"));
			}
		}
		
		return vo;
	}
	
	public List<TimeLastAnalysisVo> analysisLastTime4Type(String enterid , int day){
		String date = DataUtils.formatDate(DataUtils.getAddDay(0-day+1), "yyyy-MM-dd");
		String sql = "select type , count(1) as zs, sum(case when i.fmjb = '-1' then 1 else 0 end) as zm , sum(case when i.fmjb = '0' then 1 else 0 end) as zx, "+
							" sum(case when i.fmjb >= '1' then 1 else 0 end) as fm "+
							" from nms_key_info i where i.qyid = '"+enterid+"' and i.EVENTDATE >= '"+date+"' and sfsc ='0' group by type";
		List<Map<String , Object>> list = getJdbcTemplate().queryForList(sql);
		List<TimeLastAnalysisVo> volist = new ArrayList<TimeLastAnalysisVo>();
		TimeLastAnalysisVo zsv = new TimeLastAnalysisVo("zs");
		TimeLastAnalysisVo zmv = new TimeLastAnalysisVo("zm");
		TimeLastAnalysisVo zxv = new TimeLastAnalysisVo("zx");
		TimeLastAnalysisVo fmv = new TimeLastAnalysisVo("fm");
		volist.add(zmv);volist.add(zxv);volist.add(fmv);volist.add(zsv);
		if(list != null){
			String type = null;
			for(Map<String , Object> map : list){
				type = (String)map.get("type");
				if(type.equals("ssyq")){
					zsv.setSsyq((Long)map.get("zs"));
					zmv.setSsyq(((BigDecimal)map.get("zm")).longValue());
					zxv.setSsyq(((BigDecimal)map.get("zx")).longValue());
					fmv.setSsyq(((BigDecimal)map.get("fm")).longValue());
				} 
				if(type.equals("xwmh")){
					zsv.setXwmh((Long)map.get("zs"));
					zmv.setXwmh(((BigDecimal)map.get("zm")).longValue());
					zxv.setXwmh(((BigDecimal)map.get("zx")).longValue());
					fmv.setXwmh(((BigDecimal)map.get("fm")).longValue());
				}
				if(type.equals("lt")){
					zsv.setLt((Long)map.get("zs"));
					zmv.setLt(((BigDecimal)map.get("zm")).longValue());
					zxv.setLt(((BigDecimal)map.get("zx")).longValue());
					fmv.setLt(((BigDecimal)map.get("fm")).longValue());
				}
				if(type.equals("bk")){
					zsv.setBk((Long)map.get("zs"));
					zmv.setBk(((BigDecimal)map.get("zm")).longValue());
					zxv.setBk(((BigDecimal)map.get("zx")).longValue());
					fmv.setBk(((BigDecimal)map.get("fm")).longValue());
				}
				if(type.equals("wb")){
					zsv.setWb((Long)map.get("zs"));
					zmv.setWb(((BigDecimal)map.get("zm")).longValue());
					zxv.setWb(((BigDecimal)map.get("zx")).longValue());
					fmv.setWb(((BigDecimal)map.get("fm")).longValue());
				}
				if(type.equals("wx")){
					zsv.setWx((Long)map.get("zs"));
					zmv.setWx(((BigDecimal)map.get("zm")).longValue());
					zxv.setWx(((BigDecimal)map.get("zx")).longValue());
					fmv.setWx(((BigDecimal)map.get("fm")).longValue());
				}
				if(type.equals("sp")){
					zsv.setSp((Long)map.get("zs"));
					zmv.setSp(((BigDecimal)map.get("zm")).longValue());
					zxv.setSp(((BigDecimal)map.get("zx")).longValue());
					fmv.setSp(((BigDecimal)map.get("fm")).longValue());
				}
			}
		}
		
		
		return volist;
	}
	
	public List<KeyinfoEntity> listTopNew(String enterid , int top){
		String hql = " select i from KeyinfoEntity i where i.qyid = '"+enterid+"' and sfsc ='0' order by i.eventdate desc";
		return findByQueryString(hql, 0, top);
	}
	
	public DataGrid listTopNewByPage(String enterid , KeyinfoEntity keyinfo , int pageNum){
		String hql = " select i from KeyinfoEntity i  where i.qyid = '"+enterid+"' and sfsc = '0' ";
		
		String csql = " select count(1) from nms_key_info i where i.qyid = '"+enterid+"' and sfsc = '0' " ;
		
		if(keyinfo != null){
			
			if(StringUtil.isNotEmpty(keyinfo.getKeywordtype())){
				String sql = " select keyword from nms_key_word where lx = '"+keyinfo.getKeywordtype()+"'";
				List<String> klist = getJdbcTemplate().queryForList(sql , String.class);
				String ids = " ";
				if(klist != null)
					for(String k : klist)
						ids += ","+k;
				ids = "'"+ids.replace(",", "','")+"'";
				hql += " and i.keyword in ("+ids+")  ";
				csql += " and i.keyword in ("+ids+") ";
			}
			
			if(StringUtil.isNotEmpty(keyinfo.getStarttime())){
				hql += " and i.eventdate >= '"+keyinfo.getStarttime()+"' ";
				csql += " and i.eventdate >= '"+keyinfo.getStarttime()+"' ";
			}
			if(StringUtil.isNotEmpty(keyinfo.getEndtime())){
				hql += " and i.eventdate <= '"+keyinfo.getEndtime()+"' ";
				csql += " and i.eventdate <= '"+keyinfo.getEndtime()+"' ";
			}
			
			if(StringUtil.isNotEmpty(keyinfo.getType())){
				hql += " and i.type = '"+keyinfo.getType()+"' ";
				csql += " and i.type = '"+keyinfo.getType()+"' ";
			}
			
			if(StringUtil.isNotEmpty(keyinfo.getSfys())){
				hql += " and i.sfys = '"+keyinfo.getSfys()+"' ";
				csql += " and i.sfys = '"+keyinfo.getSfys()+"' ";
			}
			
			if(StringUtil.isNotEmpty(keyinfo.getSffm())){
				hql += " and i.sffm = '"+keyinfo.getSffm()+"' ";
				csql += " and i.sffm = '"+keyinfo.getSffm()+"' ";
			}
			
			if(StringUtil.isNotEmpty(keyinfo.getKeyword())){
				hql += " and i.keyword like '%"+keyinfo.getKeyword()+"%' ";
				csql += " and i.keyword like '%"+keyinfo.getKeyword()+"%' ";
			}
			
			if(StringUtil.isNotEmpty(keyinfo.getQuerycontent())){
				hql += " and ( i.title like '%"+keyinfo.getQuerycontent()+"%' or id in ( select id from KeyinfoTextEntity where content like '%"+keyinfo.getQuerycontent()+"%')) ";
				csql += " and ( i.title like '%"+keyinfo.getQuerycontent()+"%' or id in ( select id from nms_key_info_text where content like '%"+keyinfo.getQuerycontent()+"%')) ";
			}
			
			if(StringUtil.isNotEmpty(keyinfo.getSf())){
				hql += " and i.sf = '"+keyinfo.getSf()+"' ";
				csql += " and i.sf = '"+keyinfo.getSf()+"' ";
			}
			
			if(StringUtil.isNotEmpty(keyinfo.getFmjb())){
				hql += " and i.fmjb in ("+keyinfo.getFmjb()+") ";
				csql += " and i.sf in ("+keyinfo.getFmjb()+") ";
			}
				
		}
		
		hql += " order by i.eventdate desc ";
		Integer count = getJdbcTemplate().queryForInt(csql);
		DataGrid data = new DataGrid();
		data.setTotal(count);
		data.setPage(pageNum);
		data.setRows(50);
		data.setReaults(findByQueryString(hql, (pageNum-1)*50, 50));
		return data;
	}
	
	public List<KeyinfoEntity> ListTopFmNew(String enterid , int top){
		String hql = " select i from KeyinfoEntity i  " +
					"	where i.qyid = '"+enterid+"' and i.sffm = '1'  and sfsc ='0'  order by i.eventdate desc ";
		return findByQueryString(hql, 0, top);
	}
	
	public List<KeyinfoEntity> ListTopYjNew(String enterid , int top){
		String hql = " select i from KeyinfoEntity i " +
				"	where i.qyid = '"+enterid+"' and i.sfys = '1'  and sfsc ='0'  order by i.eventdate desc ";
	return findByQueryString(hql, 0, top);
	}
	
	public List<KeyinfoEntity> listTopTypeNew(String enterid , String type , int top){
		String hql = " select i from KeyinfoEntity i  " +
				" where i.qyid = '"+enterid+"' and i.type = '"+type+"'  and sfsc ='0'  order by i.eventdate desc ";
		return findByQueryString(hql, 0, top);
	}
	
	public List<KeyinfoEntity> listTopBadTypeNew(String enterid , String type , int top){
		String hql = " select i from KeyinfoEntity i where  " +
				" i.qyid = '"+enterid+"' and i.type = '"+type+"' and i.sffm = '1'  and sfsc ='0'  order by i.eventdate desc ";
		return findByQueryString(hql, 0, top);
	}
	
	public List<KeyinfoEntity> listLevelNew(String enterid , String fmjb , int top){
		String hql = " select i from KeyinfoEntity i where  " +
				" i.qyid = '"+enterid+"' and i.fmjb = '"+fmjb+"'  and sfsc ='0'  order by i.eventdate desc ";
		return findByQueryString(hql, 0, top);
	}
	
	public List<CommonAnalysisVo> analysisWord(String enterid , int top){
		Date date = DataUtils.getAddDay(-7);
		String datestr = DataUtils.formatDate(date, "yyyy-MM-dd");
		String sql = " select refword as name , count(1) as value from nms_key_info where qyid = '"+enterid+"' and eventdate >= '"+datestr+"'  and sfsc ='0'  group by refword order by value desc ";
		List<CommonAnalysisVo> volist =  findObjForJdbc(sql, 0, 0, CommonAnalysisVo.class, true);
		List<CommonAnalysisVo> list = new ArrayList<CommonAnalysisVo>();
		List<String> slist = new ArrayList<String>();
		String keys = null;
		CommonAnalysisVo v = null;
		for(CommonAnalysisVo vo : volist){
			keys = vo.getName();
			if(StringUtil.isNotEmpty(keys)){
				for(String key : keys.split("\\|")){
					if(slist.contains(key)){
						v = list.get(slist.indexOf(key));
						v.setValue(v.getValue()+vo.getValue());
					}else{
						v = new CommonAnalysisVo(key , vo.getValue());
						list.add(v);
						slist.add(key);
					}
				}
			}
		}
		/**
		 * 排序
		 */
		System.setProperty("java.util.Arrays.useLegacyMergeSort", "true"); 
		try {
			Collections.sort(list , new Comparator<CommonAnalysisVo>(){
				@Override
				public int compare(CommonAnalysisVo v1, CommonAnalysisVo v2){
					if(v1.getValue()>v2.getValue()) return -1;
					return 1;
				}
			});
		} catch (Exception e) {
			e.printStackTrace();
		}
		if(top>0&&list.size()>top) return list.subList(0, top);
		return list;
	}
	
	public List<CommonAnalysisVo> analysisType(String enterid , KeyinfoEntity keyinfo){
		String sql = " select type as name, count(1) as value "+
						" from nms_key_info where  qyid = '"+enterid+"'  and sfsc ='0' ";
		if(StringUtil.isNotEmpty(keyinfo.getStarttime())){
			sql += " and eventdate >= '"+keyinfo.getStarttime()+" 00:00:00' ";
		}
		
		if(StringUtil.isNotEmpty(keyinfo.getStarttime())){
			sql += " and eventdate <= '"+keyinfo.getEndtime()+" 23:59:59' ";
		}
		if(StringUtil.isNotEmpty(keyinfo.getKeyword())){
			sql += " and keyword like '%"+keyinfo.getKeyword()+"%' ";
		}
		sql += " group by type ";
		return findObjForJdbc(sql, 0, 0, CommonAnalysisVo.class, true);
	}
	
	public List<CommonAnalysisVo> analysisFmjb(String enterid , KeyinfoEntity keyinfo){
		String sql = " select fmjb as name, count(1) as value "+
				" from nms_key_info where  qyid = '"+enterid+"'  and sfsc ='0' ";
		if(StringUtil.isNotEmpty(keyinfo.getStarttime())){
			sql += " and eventdate >= '"+keyinfo.getStarttime()+" 00:00:00' ";
		}
		
		if(StringUtil.isNotEmpty(keyinfo.getStarttime())){
			sql += " and eventdate <= '"+keyinfo.getEndtime()+" 23:59:59' ";
		}
		if(StringUtil.isNotEmpty(keyinfo.getKeyword())){
			sql += " and keyword like '%"+keyinfo.getKeyword()+"%' ";
		}
		
		if(StringUtil.isNotEmpty(keyinfo.getKeywordtype())){
			sql += " and keyword in ( select keyword from nms_key_word where lx = '"+keyinfo.getKeywordtype()+"')";
		}
		
		sql += " group by fmjb order by fmjb asc";
		return findObjForJdbc(sql, 0, 0, CommonAnalysisVo.class, true);
	}
	
	public List<RefwordVo> analysisRef(String enterid , KeyinfoEntity keyinfo){
		String sql = " select fmc , fmccs , refword , refwordnum "+
				" from nms_key_info where  qyid = '"+enterid+"'  and sfsc ='0' ";
		if(StringUtil.isNotEmpty(keyinfo.getStarttime())){
			sql += " and eventdate >= '"+keyinfo.getStarttime()+" 00:00:00' ";
		}
		
		if(StringUtil.isNotEmpty(keyinfo.getStarttime())){
			sql += " and eventdate <= '"+keyinfo.getEndtime()+" 23:59:59' ";
		}
		if(StringUtil.isNotEmpty(keyinfo.getKeyword())){
			sql += " and keyword like '%"+keyinfo.getKeyword()+"%' ";
		}
		
		if(StringUtil.isNotEmpty(keyinfo.getKeywordtype())){
			sql += " and keyword in ( select keyword from nms_key_word where lx = '"+keyinfo.getKeywordtype()+"')";
		}
		return findObjForJdbc(sql, 0, 0, RefwordVo.class, true);
	}
	
	public List<CommonAnalysisVo> analysisArea(String enterid , KeyinfoEntity keyinfo){
		String sql = " select sf as name, count(1) as value "+
				" from nms_key_info where  qyid = '"+enterid+"'  and sfsc ='0' ";
		
		if(StringUtil.isNotEmpty(keyinfo.getStarttime())){
			sql += " and eventdate >= '"+keyinfo.getStarttime()+" 00:00:00' ";
		}
		
		if(StringUtil.isNotEmpty(keyinfo.getStarttime())){
			sql += " and eventdate <= '"+keyinfo.getEndtime()+" 23:59:59' ";
		}
		if(StringUtil.isNotEmpty(keyinfo.getKeyword())){
			sql += " and keyword like '%"+keyinfo.getKeyword()+"%' ";
		}
		sql += " group by sf order by value desc";
		return findObjForJdbc(sql, 0, 0, CommonAnalysisVo.class, true);
	}
	
	public List<CommonAnalysisVo> analysisSite(String enterid , KeyinfoEntity keyinfo , int top){
		String sql = " select  s.mc as name , i.mycount as value "+
				" from nms_site s left join " +
				" ( select site , count(1) as mycount from nms_key_info "+
				" where  qyid = '"+enterid+"'  and sfsc ='0' ";
		if(StringUtil.isNotEmpty(keyinfo.getStarttime())){
			sql += " and eventdate >= '"+keyinfo.getStarttime()+" 00:00:00' ";
		}
		
		if(StringUtil.isNotEmpty(keyinfo.getStarttime())){
			sql += " and eventdate <= '"+keyinfo.getEndtime()+" 23:59:59' ";
		}
		if(StringUtil.isNotEmpty(keyinfo.getKeyword())){
			sql += " and keyword like '%"+keyinfo.getKeyword()+"%' ";
		}
		sql += " group by site) i  on s.mc = i.site ";
		sql += " order by value desc limit 0 ,"+top;
		return findObjForJdbc(sql, 0, top, CommonAnalysisVo.class, true);
	}
	
	
	
	public List<CommonAnalysisVo> analysisBad(String enterid , KeyinfoEntity keyinfo ){
		String sql = "select DATE_FORMAT(EVENTDATE,'%Y-%m-%d') as name , count(1) as value	from nms_key_info where qyid = '"+enterid+"' and sffm ='1'  and sfsc ='0'  ";
		if(keyinfo != null){
			if(StringUtil.isNotEmpty(keyinfo.getStarttime())){
				sql += " and EVENTDATE >= '"+keyinfo.getStarttime()+"' ";
			}
			
			if(StringUtil.isNotEmpty(keyinfo.getStarttime())){
				sql += " and EVENTDATE <= '"+keyinfo.getEndtime()+" 23:59:59' ";
			}
			
			if(StringUtil.isNotEmpty(keyinfo.getKeyword())){
				sql += " and keyword like '%"+keyinfo.getKeyword()+"%' ";
			}
		}
		sql +=	" group by name order by name asc ";
		
		List<CommonAnalysisVo> list = findObjForJdbc(sql, 0, 0, CommonAnalysisVo.class, true);
		
		Date startdate = DataUtils.parseDate(keyinfo.getStarttime(), "yyyy-MM-dd");
		String endtime = keyinfo.getEndtime();
		Calendar cl = Calendar.getInstance();
		cl.setTime(startdate);
		String starttime = DataUtils.formatDate(cl.getTime(), "yyyy-MM-dd");
		while(starttime.compareTo(endtime)<=0){
			if(!list.contains(new CommonAnalysisVo(starttime , 0))){
				list.add(new CommonAnalysisVo(starttime , 0));
			}
			cl.add(Calendar.DAY_OF_MONTH, 1);
			starttime = DataUtils.formatDate(cl.getTime(), "yyyy-MM-dd");
		}
		Collections.sort(list , new Comparator<CommonAnalysisVo>() {
			@Override
			public int compare(CommonAnalysisVo v1, CommonAnalysisVo v2) {
				return v1.getName().compareTo(v2.getName());
			}
		});
		
		
		return list;
	}
	
	public List<CommonAnalysisVo> analysisBad4Type(String enterid , KeyinfoEntity keyinfo){
		String sql = "select type as name , count(1) as value	from nms_key_info where qyid = '"+enterid+"' and sffm ='1'  and sfsc ='0'  ";
		if(keyinfo != null){
			if(StringUtil.isNotEmpty(keyinfo.getStarttime())){
				sql += " and EVENTDATE >= '"+keyinfo.getStarttime()+"' ";
			}
			
			if(StringUtil.isNotEmpty(keyinfo.getStarttime())){
				sql += " and EVENTDATE <= '"+keyinfo.getEndtime()+" 23:59:59' ";
			}
			if(StringUtil.isNotEmpty(keyinfo.getKeyword())){
				sql += " and keyword like '%"+keyinfo.getKeyword()+"%' ";
			}
		}
		sql +=	" group by name order by type asc ";
		List<CommonAnalysisVo> list = findObjForJdbc(sql, 0, 0, CommonAnalysisVo.class, true);
		return list;
	}
	
	public List<CommonAnalysisVo> analysisBad4Site(String enterid , KeyinfoEntity keyinfo){
		String sql = "select site as name , count(1) as value	from nms_key_info where qyid = '"+enterid+"' and sffm ='1'  and sfsc ='0'  ";
		if(keyinfo != null){
			if(StringUtil.isNotEmpty(keyinfo.getStarttime())){
				sql += " and EVENTDATE >= '"+keyinfo.getStarttime()+"' ";
			}
			
			if(StringUtil.isNotEmpty(keyinfo.getStarttime())){
				sql += " and EVENTDATE <= '"+keyinfo.getEndtime()+" 23:59:59' ";
			}
			if(StringUtil.isNotEmpty(keyinfo.getKeyword())){
				sql += " and keyword like '%"+keyinfo.getKeyword()+"%' ";
			}
		}
		sql +=	" group by site order by value desc ";
		List<CommonAnalysisVo> list = findObjForJdbc(sql, 0, 10, CommonAnalysisVo.class, true);
		return list;
	}
	
	public List<KeyinfoEntity> listAfterTime(Date logintime , KeyinfoEntity keyinfo , int top){
		String hql = " from KeyinfoEntity where cjsj >= '"+DataUtils.formatDate(logintime, "yyyy-MM-dd HH:mm:ss")+"'  and sfsc ='0'  ";
		
		if(keyinfo != null){
			if(StringUtil.isNotEmpty(keyinfo.getSfys()))
				hql += " and sfys = '"+keyinfo.getSfys()+"' ";
			if(StringUtil.isNotEmpty(keyinfo.getSffm()))
				hql += " and sffm = '"+keyinfo.getSffm()+"'";
		}
		hql += " and qyid = '"+keyinfo.getQyid()+"' ";
		
		hql += " order by fmz desc ";
		
		return findByQueryString(hql,0,top); 
		
	}
	
	public int countAfterTime(Date logintime , KeyinfoEntity keyinfo){
		String sql = " select count(1) from nms_key_info where  cjsj >= '"+DataUtils.formatDate(logintime, "yyyy-MM-dd HH:mm:ss")+"'  and sfsc ='0'  ";
		if(keyinfo != null){
			if(StringUtil.isNotEmpty(keyinfo.getSfys()))
				sql += " and sfys = '"+keyinfo.getSfys()+"' ";
			if(StringUtil.isNotEmpty(keyinfo.getSffm()))
				sql += " and sffm = '"+keyinfo.getSffm()+"'";
		}
		
		sql += " and qyid = '"+keyinfo.getQyid()+"'";
		return getJdbcTemplate().queryForInt(sql);
	}
}